﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseOverduesetting;
using SHZY.BaseData.Entitys;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Entitys.Entity;
using SHZY.Common.Core.Manager.Files;
using SHZY.BaseData.Entitys.Dto.DictionaryData;
using Serilog.Events;
using SHZY.Systems.Entitys.Dto.MessageTemplate;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using SHZY.BaseData.Entitys.Dto.QmsBaseDefect;
using SHZY.Common.Helper;
using SHZY.BaseData.Entitys.Dto.Overduesetting;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：红绿灯设置.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "QmsBaseOverduesetting", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseOverduesettingService : IQmsBaseOverduesettingService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseOverduesettingEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 文件管理.
    /// </summary>
    private readonly IFileManager _fileManager;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseOverduesettingService"/>类型的新实例.
    /// </summary>
    public QmsBaseOverduesettingService(
        ISqlSugarRepository<QmsBaseOverduesettingEntity> qmsBaseOverduesettingRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager,
        IFileManager fileManager)
    {
        _repository = qmsBaseOverduesettingRepository;
        _dataInterfaceService = dataInterfaceService;
        _db = context.AsTenant();
        _userManager = userManager;
        _fileManager = fileManager;
    }

    /// <summary>
    /// 获取红绿灯设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        try
        {
            var query = (await _repository.FirstOrDefaultAsync(x => x.Id == id));
            QmsBaseOverduesettingInfoOutput output = new QmsBaseOverduesettingInfoOutput()
            {
                id = query.Id,
                type = query.Type,
                timeUnit = query.TimeUnit,
                status = query.Status,
                minValue = query.MinValue,
                enabledMark = query.EnabledMark,
                maxValue = query.MaxValue,
                messageTemplate = query.MessageTemplate,
                recipientList = query.RecipientList.Split(',').ToList()
            };

            return output;
        }
        catch (Exception ex)
        {

            throw ex;
        }

    }

    /// <summary>
    /// 获取红绿灯设置列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseOverduesettingListQueryInput input)
    {
        var recipientList = input.recipientList?.Split(',').ToList().Last();
        var data = await _repository.Context.Queryable<QmsBaseOverduesettingEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.type), it => it.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.status), it => it.Status.Equals(input.status))
            .WhereIF(!string.IsNullOrEmpty(input.timeUnit), it => it.TimeUnit.Equals(input.timeUnit))
            .WhereIF(!string.IsNullOrEmpty(input.recipientList), it => it.RecipientList.Contains(recipientList))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Type.Contains(input.keyword) || it.Status.Contains(input.keyword) || it.TimeUnit.Contains(input.keyword) || it.RecipientList.Contains(input.keyword))
            .Where(it => it.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseOverduesettingListOutput
            {
                id = it.Id,
                type = SqlFunc.Subqueryable<DictionaryDataEntity>().Where(dic => dic.Id.Equals(it.Type) && dic.DictionaryTypeId.Equals("459581510966602757")).Select(dic => dic.FullName),
                minValue = it.MinValue,
                maxValue = it.MaxValue,
                recipientList = it.RecipientList,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
                status = it.Status,
                timeUnit = it.TimeUnit,
                messageTemplate = it.MessageTemplate,
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);

        await _repository.Context.ThenMapperAsync(data.list, async item =>
        {
            // 状态，即将逾期=1 逾期=2
            var statusDataJson = "[{\"id\":\"1\",\"fullName\":\"即将逾期\"},{\"id\":\"2\",\"fullName\":\"逾期\"}]";
            var statusData = JsonConvert.DeserializeObject<List<StaticDataModel>>(statusDataJson);
            item.status = statusData.Find(it => item.status.Equals(it.id)).fullName;

            // 时间单位 day=天 hour=小时 minute=分钟 second=秒
            var timeUnitData = "[{\"id\":\"day\",\"fullName\":\"天\"},{\"id\":\"hour\",\"fullName\":\"小时\"},{\"id\":\"minute\",\"fullName\":\"分钟\"},{\"id\":\"second\",\"fullName\":\"秒\"}]".ToObject<List<StaticDataModel>>();
            item.timeUnit = timeUnitData.Find(it => item.timeUnit.Equals(it.id)).fullName;

            // 消息接收人
            item.recipientList = string.Join(",", await _repository.Context.Queryable<UserEntity>().Where(a => item.recipientList.Contains(a.Id)).Select(a => a.RealName).ToListAsync());

            // 消息模板
            item.messageTemplate = string.Join(",", await _repository.Context.Queryable<MessageTemplateEntity>().Where(a => item.messageTemplate.Contains(a.Id)).Select(a => a.FullName).ToListAsync());
        });

        return PageResult<QmsBaseOverduesettingListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 加载逾期设置信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("List")]
    public async Task<dynamic> GetOverdueList()
    {
        var _list = await _repository.Context.Queryable<QmsBaseOverduesettingEntity>().Where(s => s.EnabledMark == 1 && s.DeleteMark == null)
            .OrderBy(o => o.Status,OrderByType.Asc)
            .ToListAsync();
        var settingList = _list.Select(it => new QmsBaseOverduesettingInfoOutput
        {
            id = it.Id,
            type = it.Type,
            minValue = it.MinValue,
            maxValue = it.MaxValue,
            recipientList = it.RecipientList.Split(',').ToList(),
            messageTemplate = it.MessageTemplate,
            status = it.Status,
            enabledMark = it.EnabledMark,
            timeUnit = it.TimeUnit,
        }).ToList();

        var data = (await _repository.Context.Queryable<DictionaryDataEntity>().Where(x => x.DictionaryTypeId.Equals("459581510966602757"))
            .OrderBy(o => o.SortCode,OrderByType.Asc)
            .Select(it => new { enCode = it.EnCode, enName = it.FullName }).ToListAsync())
            .Adapt<List<QmsBaseOverdusettingInfoListOutput>>();

        foreach (var item in data)
        {
            item.overdueSettings = settingList.FindAll(x => x.type.Equals(item.enCode));
        }

        return data;
    }

    /// <summary>
    /// 新建红绿灯设置.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseOverduesettingCrInput input)
    {
        var entity = input.Adapt<QmsBaseOverduesettingEntity>();
        entity.RecipientList = "";
        for (int i = 0; i < input.recipientList.Count; i++)
        {
            entity.RecipientList += input.recipientList[i];
            if (i != input.recipientList.Count - 1)
            {
                entity.RecipientList += ",";
            }
        }
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity)
            .IgnoreColumns(ignoreNullColumn: true)
            .CallEntityMethod(m => m.Creator())
            .ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 提交逾期设置.
    /// </summary>
    /// <param name="inputs">参数.</param>
    /// <returns></returns>
    [HttpPost("submit")]
    public async Task CreateOrUpdate([FromBody] List<QmsBaseOverduesettingUpInput> inputs)
    {
        var entityList = inputs.Adapt<List<QmsBaseOverduesettingEntity>>();
        for (int i = 0;i < inputs.Count;i++)
        {
            entityList[i].RecipientList = "";
            for (int j = 0; j < inputs[i].recipientList.Count; j++)
            {
                entityList[i].RecipientList += inputs[i].recipientList[j];
                if (j != inputs[i].recipientList.Count - 1)
                {
                    entityList[i].RecipientList += ",";
                }
            }
        }
        try
        {
            var CreateList = entityList.FindAll(f => string.IsNullOrEmpty(f.Id));

            var UpdateList = entityList.FindAll(f => !string.IsNullOrEmpty(f.Id));

            _db.BeginTran();

            if (CreateList != null && CreateList.Count > 0)
            {
                await _repository.Context.Insertable(CreateList).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
            }
            if (UpdateList != null && UpdateList.Count > 0)
            {
                await _repository.Context.Updateable(UpdateList).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
            }
            _db.CommitTran();
        }
        catch (Exception)
        {
            _db.RollbackTran();
            throw Oops.Oh(ErrorCode.COM1008);
        }
    }

    /// <summary>
    /// 获取红绿灯设置无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseOverduesettingListQueryInput input)
    {
        var recipientList = input.recipientList?.Split(',').ToList().Last();
        List<QmsBaseOverduesettingListOutput> data = await _repository.Context.Queryable<QmsBaseOverduesettingEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.type), it => it.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.status), it => it.Status.Equals(input.status))
            .WhereIF(!string.IsNullOrEmpty(input.timeUnit), it => it.TimeUnit.Equals(input.timeUnit))
            .WhereIF(!string.IsNullOrEmpty(input.recipientList), it => it.RecipientList.Contains(recipientList))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Type.Contains(input.keyword) || it.Status.Contains(input.keyword) || it.TimeUnit.Contains(input.keyword) || it.RecipientList.Contains(input.keyword))
            .Where(it => it.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseOverduesettingListOutput
            {
                id = it.Id,
                type = SqlFunc.Subqueryable<DictionaryDataEntity>().Where(dic => dic.Id.Equals(it.Type) && dic.DictionaryTypeId.Equals("459581510966602757")).Select(dic => dic.FullName),
                minValue = it.MinValue,
                maxValue = it.MaxValue,
                recipientList = it.RecipientList,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
                status = it.Status,
                timeUnit = it.TimeUnit,
                messageTemplate = it.MessageTemplate,
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();

        await _repository.Context.ThenMapperAsync(data, async item =>
        {
            // 状态，即将逾期=1 逾期=2
            var statusDataJson = "[{\"id\":\"1\",\"fullName\":\"即将逾期\"},{\"id\":\"2\",\"fullName\":\"逾期\"}]";
            var statusData = JsonConvert.DeserializeObject<List<StaticDataModel>>(statusDataJson);
            item.status = statusData.Find(it => item.status.Equals(it.id)).fullName;

            // 时间单位 day=天 hour=小时 minute=分钟 second=秒
            var timeUnitData = "[{\"id\":\"day\",\"fullName\":\"天\"},{\"id\":\"hour\",\"fullName\":\"小时\"},{\"id\":\"minute\",\"fullName\":\"分钟\"},{\"id\":\"second\",\"fullName\":\"秒\"}]".ToObject<List<StaticDataModel>>();
            item.timeUnit = timeUnitData.Find(it => item.timeUnit.Equals(it.id)).fullName;

            // 消息接收人
            item.recipientList = string.Join(",", await _repository.Context.Queryable<UserEntity>().Where(a => item.recipientList.Contains(a.Id)).Select(a => a.RealName).ToListAsync());

            // 消息模板
            item.messageTemplate = string.Join(",", await _repository.Context.Queryable<MessageTemplateEntity>().Where(a => item.messageTemplate.Contains(a.Id)).Select(a => a.FullName).ToListAsync());
        });

        return data;
    }

    /// <summary>
    /// 导出红绿灯设置.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseOverduesettingListQueryInput input)
    {
        var exportData = new List<QmsBaseOverduesettingListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseOverduesettingListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"单据类型\",\"field\":\"type\"},{\"value\":\"状态\",\"field\":\"status\"},{\"value\":\"时间单位\",\"field\":\"timeUnit\"},{\"value\":\"时间最小值\",\"field\":\"minValue\"},{\"value\":\"时间最大值\",\"field\":\"maxValue\"},{\"value\":\"消息接收人\",\"field\":\"recipientList\"},{\"value\":\"消息模板\",\"field\":\"messageTemplate\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "红绿灯设置.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseOverduesettingListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除红绿灯设置.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseOverduesettingEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除​缺陷类别
                var isOk = await _repository.Context
                .Updateable<QmsBaseOverduesettingEntity>()
                .SetColumns(it => new QmsBaseOverduesettingEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id))
                .ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新红绿灯设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseOverduesettingUpInput input)
    {
        var entity = input.Adapt<QmsBaseOverduesettingEntity>();
        entity.RecipientList = "";
        for (int i = 0; i < input.recipientList.Count; i++)
        {
            entity.RecipientList += input.recipientList[i];
            if (i != input.recipientList.Count - 1)
            {
                entity.RecipientList += ",";
            }
        }
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.Type,
            it.Status,
            it.TimeUnit,
            it.MinValue,
            it.MaxValue,
            it.RecipientList,
            it.MessageTemplate,
            it.EnabledMark,
            it.LastModifyTime,
            it.LastModifyUserId,
        }).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除红绿灯设置.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<QmsBaseOverduesettingEntity>()
               .SetColumns(it => new QmsBaseOverduesettingEntity()
               {
                   DeleteTime = DateTime.Now,
                   DeleteMark = 1,
                   DeleteUserId = _userManager.UserId
               }).Where(x => x.Id == id)
               .ExecuteCommandHasChangeAsync();
        if (!isOk) throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 获取客户类型列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("getMessageTemplateList")]
    public async Task<dynamic> GetMessageTemplateList()
    {
        var data = await _repository.Context.Queryable<MessageTemplateEntity>()
        .Where(it => it.DeleteMark == null)
        .Select(it => new
        {
            it.Id,
            it.FullName
        }).ToListAsync();
        return data;
    }

    /// <summary>
    /// 上传文件.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("Uploader")]
    public async Task<dynamic> Uploader(IFormFile file)
    {
        try
        {
            var _filePath = _fileManager.GetPathByType(string.Empty);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
            var stream = file.OpenReadStream();
            await _fileManager.UploadFileByType(stream, _filePath, _fileName);
            return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };

        }
        catch (Exception)
        {
            throw Oops.Oh(ErrorCode.D8001);
        }
    }

    /// <summary>
    /// 导入数据.
    /// </summary>
    /// <param name="input">请求参数</param>
    /// <returns></returns>
    [HttpPost("ImportData")]
    public async Task<dynamic> ImportData([FromBody] QmsBaseOverduesettingInput input)
    {
        var output = new QmsBaseOverduesettingImportDataOutput();
        foreach (var item in input.list)
        {
            try
            {
                if (!string.IsNullOrEmpty(item.maxValue))
                {
                    System.Text.RegularExpressions.Regex regex = new
                    System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
                    if (!regex.IsMatch(item.maxValue.ToString()))
                    {
                        item.exceptionMsg = "时间最大值应该为整数！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                }

                if (!string.IsNullOrEmpty(item.minValue))
                {
                    System.Text.RegularExpressions.Regex regex = new
                    System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
                    if (!regex.IsMatch(item.minValue.ToString()))
                    {
                        item.exceptionMsg = "时间最小值应该为整数！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                }
                if (Convert.ToInt32(item.maxValue)< Convert.ToInt32(item.minValue))
                {
                    item.exceptionMsg = "时间最大值不能小于时间最小值！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }

                var entity = item.Adapt<QmsBaseOverduesettingEntity>();

                //验证参数信息
                if (string.IsNullOrEmpty(entity.Type))
                {
                    item.exceptionMsg = "请输入单据类型！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }

                var Dicdata = await _repository.Context
                            .Queryable<DictionaryDataEntity>()
                            .Where(it => it.DeleteMark == null && entity.Type.Equals(it.FullName))
                            .ToListAsync();
                entity.Type = Dicdata.First().Id;

                if (string.IsNullOrEmpty(entity.Status))
                {
                    item.exceptionMsg = "请输入状态！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }

                entity.Status = entity.Status == "即将逾期" ? "1" : "2";

                if (string.IsNullOrEmpty(entity.TimeUnit))
                {
                    item.exceptionMsg = "请输入时间单位！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                switch (entity.TimeUnit)
                {
                    case "天":
                        entity.TimeUnit =  "day";
                        break;
                    case "小时":
                        entity.TimeUnit = "hour";
                        break;
                    case "分钟":
                        entity.TimeUnit = "minute";
                        break;
                    case "秒":
                        entity.TimeUnit = "second";
                        break;
                }
                if (string.IsNullOrEmpty(entity.RecipientList))
                {
                    item.exceptionMsg = "请输入消息接收人！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (entity.RecipientList.Contains(","))
                {
                    var userlist = entity.RecipientList.Split(',').ToList();
                    var Cusdata = await _repository.Context
                        .Queryable<UserEntity>()
                        .Where(it => it.DeleteMark == null && userlist.Contains(it.Account))
                        .ToListAsync();
                    if (Cusdata.Count <= 0 || userlist.Count != Cusdata.Count)
                    {
                        item.exceptionMsg = "消息接收人的账号有误或者未用逗号分隔！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                    entity.RecipientList = "";
                    for (int i = 0; i < Cusdata.Count; i++)
                    {
                        if (i == Cusdata.Count - 1)
                        {
                            entity.RecipientList += Cusdata[i].Id;
                        }
                        else
                        {
                            entity.RecipientList += Cusdata[i].Id + ",";
                        }
                    }
                }
                else
                {
                    var Cusdata = await _repository.Context
                        .Queryable<UserEntity>()
                        .Where(it => it.DeleteMark == null && entity.RecipientList.Contains(it.Account))
                        .ToListAsync();

                    if (Cusdata.Count <= 0)
                    {
                        item.exceptionMsg = "消息接收人的账号有误或者未用逗号分隔！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }

                    entity.RecipientList = Cusdata.FirstOrDefault().Id;
                }

                if (string.IsNullOrEmpty(entity.MessageTemplate))
                {
                    item.exceptionMsg = "请输入消息模板！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }

                var massagedata = await _repository.Context.Queryable<MessageTemplateEntity>()
                        .Where(it => it.DeleteMark == null && it.FullName == entity.MessageTemplate).ToListAsync();

                entity.MessageTemplate = massagedata.FirstOrDefault().Id;
                entity.EnabledMark = 0;

                var isOK = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOK < 1)
                {
                    output.failResult.Add(item);
                    output.fnum++;
                }
                else
                {
                    output.snum++;
                }
            }
            catch (Exception ex)
            {
                item.exceptionMsg = ex.Message;
                output.failResult.Add(item);
                output.fnum++;
            }
        }
        if (output.snum == input.list.Count)
        {
            output.resultType = 1;
        }
        else
        {
            output.resultType = 0;
        }
        return output;
    }

    /// <summary>
    /// 模板下载.
    /// </summary>
    /// <returns></returns>
    [HttpGet("TemplateDownload")]
    public async Task<dynamic> TemplateDownload()
    {
        string _fileName = "红绿灯模板.xlsx";
        var filePath = Path.Combine(FileVariable.TemplateFilePath, "Overduesetting_import_template.xlsx"); // 模板路径
        var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
        if (!(await _fileManager.ExistsFile(addFilePath)))
        {
            var stream = await _fileManager.GetFileStream(filePath);
            await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
        }

        return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
    }

    /// <summary>
    /// 导入预览.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("ImportPreview")]
    public async Task<dynamic> ImportPreview(string fileName)
    {
        try
        {
            var filePath = FileVariable.TemporaryFilePath;
            var savePath = Path.Combine(filePath, fileName);
            // 得到数据
            var sr = await _fileManager.GetFileStream(savePath);
            var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
            foreach (var item in excelData.Columns)
            {
                excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
            }
            // 删除文件
            await _fileManager.DeleteFile(savePath);
            // 返回结果
            return new { dataRow = excelData };
        }
        catch (Exception)
        {
            throw Oops.Oh(ErrorCode.D1801);
        }
    }

    #region PrivateMethod
    private string GetFileEncode(string filed)
    {
        switch (filed)
        {
            case "单据类型":
                return "Type";
            case "状态":
                return "Status";
            case "时间单位":
                return "TimeUnit";
            case "时间最小值":
                return "MinValue";
            case "时间最大值":
                return "MaxValue";
            case "消息接收人":
                return "RecipientList";
            case "消息模板":
                return "MessageTemplate";
            default:
                return string.Empty;
        }
    }
    #endregion
}
